<template>
  <div class="app-container">
      <h2 style="text-align:center;">发布新课程</h2>

        <el-steps :active="active" process-status="process" align-center   finish-status="success">
            <el-step title="填写课程基本信息"></el-step>
            <el-step title="填写课程大纲"></el-step>
            <el-step title="发布课程"></el-step>
        </el-steps>
      


        <el-form label-width="120px">

            <el-form-item label="课程标题">
                <el-input v-model="courseInfo.title" placeholder="示例：Java入门"  />
            </el-form-item>

            <!--所属分类 -->
            <el-form-item label="课程所属分类">
                <!-- 一级分类 -->
               <el-select v-model="courseInfo.courseTypeParentId" 
                    placeholder="请选择一级分类" @change="oneTypeChanged">
                  <el-option 
                    v-for="getOneCourseType in courseTypeOne"
                    :label="getOneCourseType.typeName" :value="getOneCourseType.id"
                    :key="getOneCourseType.id" ></el-option>
                </el-select>
                <!-- 二级分类 -->
                <el-select v-model="courseInfo.courseTypeId" 
                    placeholder="请选择二级分类" @change="doRefresh">
                  <el-option 
                    v-for="getTwoCourseType in courseTypeTwo"
                    :label="getTwoCourseType.typeName" :value="getTwoCourseType.id"
                    :key="getTwoCourseType.id" ></el-option>
                </el-select>

            </el-form-item>

            <!--课程教师-->
            <el-form-item label="课程教师">
                <el-select v-model="courseInfo.teacherId" 
                    placeholder="请选择教师">
                  <el-option 
                    v-for="teacher in teacherList"
                    :label="teacher.name" :value="teacher.id"
                    :key="teacher.id" ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="总课时">
                <el-input-number :min="0" v-model="courseInfo.totalHours" controls-position="right" placeholder="请填写课程的总课时数"/>
            </el-form-item>

            <!--课程简介 -->
            <el-form-item label="课程简介">
                <!-- <el-input v-model="courseInfo.description"  /> -->
                <tinymce :height="300" v-model="courseInfo.description" ref="content" id="content"/>
            </el-form-item>

            <!--课程封面 -->
            <el-form-item label="课程封面">
                <!-- <el-upload 
                    :action="BASE_API+'/eduoss/fileoss'"
                    :show-file-list="false"
                    :on-success="imgSuccess"
                    :before-upload="beforeimgUpload"
                    class="avatar-uploader">
                  <img :src="courseInfo.cover">
                </el-upload> -->
                <el-upload
                    class="avatar-uploader"
                    :action="BASE_API+'/eduoss/fileoss'"
                    :show-file-list="false"
                    :on-success="imgSuccess"
                    :before-upload="beforeimgUpload">
                    <img v-if="cover" :src="cover" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>

            <el-form-item label="课程价格">
                <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
            </el-form-item>
            

            <el-form-item>
                <el-button @click="saveOrUpdate()" type="primary" :disabled="saveBtnDisables">保存并下一步</el-button>
            </el-form-item>
        </el-form>
        

  </div>
</template>

<script>
import course from '@/api/course/course'
import teachers from '@/api/teacher/teacher'
import courseType from '@/api/course/courseType'
import Tinymce from '@/components/Tinymce'

  export default {
    components:{Tinymce},
    data() {
      return {
        active: 0,
        saveBtnDisables:false,
        courseInfo:{
            title: '',
            courseTypeId:'',//二级分类id
            courseTypeParentId:'',//一级分类id
            totalHours:'',
            description:'',
            cover:'',
            price: 0
        },
        cover:'',
        teacherList:[],
        courseTypeOne:[],//一级分类
        courseTypeTwo:[],//二级分类
        BASE_API:process.env.BASE_API,
        courseId:''
      };
    },
    created(){
        this.init()
        
    },
    //路由监听
    watch:{
        //路由变化，以下方法执行
        $route(to,from){
            this.init()

        }
    },

    methods: {
        //初始化
        init(){
            //判断路径是否有id值
            if(this.$route.params && this.$route.params.id){
                this.courseId = this.$route.params.id
                this.getCourseInfoById(this.courseId)
            }else{
                //清空数据
                this.courseInfo={}
                this.courseInfo.description=''
                //初始化所有教师：显示教师下拉列表
                this.getAllTeacher()
                //初始化一级分类
                this.getOneCourseType()
                
            }
        },
        //添加课程
        addCourse(){
            course.addCourseInfo(this.courseInfo)
                .then(response =>{
                    this.$message({
                        type: 'success',
                        message: '添加课程信息成功!'
                    });
                    //跳转到第二步
                    this.$router.push({path:'/course/courseChapter/'+response.data.cId})
                })
            
        },
        //修改课程
        updateCourse(courseInfo){
            course.updateCourseInfo(courseInfo)
                .then(response =>{
                    //提示成功
                    this.$message({
                            type: 'success',
                            message: '修改课程信息成功!'
                    });
                    //跳转到第二步
                    this.$router.push({path:'/course/courseChapter/'+this.courseId})
                })
        },

        //添加或课程信息
        saveOrUpdate() {
            //判断添加或修改
            if(!this.courseInfo.id){
                //添加
                this.addCourse()
            }else{
                //修改
                this.updateCourse(this.courseInfo)
            }
        },
        //查询所有教师
        getAllTeacher(){
            teachers.getAllTeacher()
                .then(response =>{
                    this.teacherList = response.data.datas
                })
        },
        //查询所有一级分类
        getOneCourseType(){
            courseType.getCourseTypeListPage()
                .then(response =>{
                    this.courseTypeOne = response.data.list
                    console.log(response.data.list)
                })
        },
        //一级分类修改后
        oneTypeChanged(value){
            for(let i = 0 ; i < this.courseTypeOne.length ; i++ ){
                //每个一级分类
                let oneType = this.courseTypeOne[i]
                //判断id是否一致
                if(value === oneType.id){
                    //获取所有二级分类
                    this.courseTypeTwo = oneType.children
                    //清空二级分类
                    this.courseInfo.courseTypeId = ''
                }
            }
            console.log(this.courseTypeTwo)
        },
        //二级分类改变后
        doRefresh(){
            this.$forceUpdate()
        },
        //上传成功
        imgSuccess(res,file){
            console.log(res)
            this.courseInfo.cover = res.data.url
            this.cover = res.data.url
            console.log(this.courseInfo.cover)

        },
        //上传之前
        beforeimgUpload(file){
            const isJPG = file.type === 'image/jpeg'
            const isLimit2M = file.size / 1024 / 1024 < 2

            if(!isJPG){
                this.$message.error('上传图片只能是JPG格式！')
            }
            if(!isLimit2M){
                this.$message.error('上传大小不能超过2MB！')
            }

            //图片格式 宽度==600 为 1 ；长度==400 为 1
            const isSize = new Promise(function(resolve, reject) {
                            let width = 600;
                            let height = 400;
                            let _URL = window.URL || window.webkitURL;
                            let img = new Image();
                            img.onload = function() {
                                    let valid = img.width == width && img.height == height;
                                    valid ? resolve() : reject();
                            }
                            img.src = _URL.createObjectURL(file);
                    }).then(() => {
                            return file;
                    }, () => {
                            this.$message.error('上传的图片格式为：600*400！');
                            return Promise.reject();
                    });

            return isJPG && isLimit2M && isSize
        },
        //根据课程id查询课程基本信息
        getCourseInfoById(id){
            course.getChapter(id)
                .then(response =>{
                    this.courseInfo = response.data.courseInfoVo
                    this.cover = response.data.courseInfoVo.cover
                    //查询所有一级和二级分类
                    courseType.getCourseTypeListPage()
                        .then(response =>{
                            //获取所有一级分类
                            this.courseTypeOne = response.data.list

                            //遍历所有一级分类数组
                            for(var i = 0 ; i < this.courseTypeOne.length ; i++){
                                var oneCourseType = this.courseTypeOne[i]
                                if(this.courseInfo.courseTypeParentId === oneCourseType.id){
                                    //获取一级分类所有二级分类
                                    this.courseTypeTwo = oneCourseType.children
                                }
                            }
                        })
                        //初始化所有教师
                        this.getAllTeacher()
                })
        }
    }
  }
</script>
<style scoped>
.tinymce-container{
    line-height: 30px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 300px;
    height: 200px;
    display: block;
  }
</style>